//
//  PhotoView.m
//  Shows
//
//  Created by Roc on 11-4-15.
//  Copyright 2011年 __MyCompanyName__. All rights reserved.
//

#import "PhotoView.h"

#import "ASIHTTPRequest.h"

@implementation PhotoView

@synthesize index = _index;

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        
    }
    return self;
}

- (id)init {
    if ((self = [super init])) {
        _responseData = [[NSMutableData alloc] init];
    }
    
    return self;
}

/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect
{
    // Drawing code
}
*/

- (void)dealloc
{
    [super dealloc];
}

- (void)load:(NSString*)urlPath
{
    _urlPath = [urlPath retain];
    
    
    NSURL *url = [NSURL URLWithString:urlPath];
    ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
    [request setDownloadProgressDelegate:self];
    [request setDelegate:self];
    [request startAsynchronous];
    
    if (!_statusSpinner) {
        _statusSpinner = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:
                              UIActivityIndicatorViewStyleWhiteLarge];
        [self addSubview:_statusSpinner];
    }
        
    [_statusSpinner startAnimating];
    _statusSpinner.hidden = NO;
        

    
    /*
    NSURL* requestUrl = [NSURL URLWithString:urlPath];
    NSURLRequest* request = [NSURLRequest requestWithURL:requestUrl];
    
    _connection = [NSURLConnection connectionWithRequest:request delegate:self]; 
     */
}

- (void)clean{
    self.image = nil;
    [_urlPath release];
    _urlPath = nil;
    [self setNeedsLayout];
}
#pragma mark -
#pragma mark Common

///////////////////////////////////////////////////////////////////////////////////////////////////
UIInterfaceOrientation InterfaceOrientation() {
    UIInterfaceOrientation orient = [UIApplication sharedApplication].statusBarOrientation;
    if (UIDeviceOrientationUnknown == orient) {
        return [UIApplication sharedApplication].statusBarOrientation;
        
    } else {
        return orient;
    }
}

///////////////////////////////////////////////////////////////////////////////////////////////////
CGRect ScreenBounds() {
    CGRect bounds = [UIScreen mainScreen].bounds;
    if (UIInterfaceOrientationIsLandscape(InterfaceOrientation())) {
        CGFloat width = bounds.size.width;
        bounds.size.width = bounds.size.height;
        bounds.size.height = width;
    }
    return bounds;
}


#pragma mark -
#pragma mark UIView


///////////////////////////////////////////////////////////////////////////////////////////////////
- (void)layoutSubviews {
    [super layoutSubviews];
    
    _statusSpinner.frame =
            CGRectMake(floor(self.bounds.size.width/2 - _statusSpinner.frame.size.width/2),
                       floor(self.bounds.size.height/2- _statusSpinner.frame.size.height/2),
                       _statusSpinner.frame.size.width, _statusSpinner.frame.size.height);
    
}

#pragma mark - 
#pragma mark ASIHTTPRequestDelegate

///////////////////////////////////////////////////////////////////////////////////////////////////
- (void)requestFinished:(ASIHTTPRequest *)request
{
    int statusCode = [request responseStatusCode];
    NSLog(@"%@-- %d requestFinished", _urlPath, statusCode);
    

    [_statusSpinner stopAnimating];
    _statusSpinner.hidden = YES;

    // Use when fetching binary data
    NSData *responseData = [request responseData];
    
       // We need to accept valid HTTP status codes, not only 200.
    if (statusCode >= 200 && statusCode < 300) {
        self.image = [UIImage imageWithData:responseData];
        [self setNeedsDisplay];
        //[self setNeedsLayout];
    } else if (_response.statusCode == 304) {
        
    } else {
    }

}

///////////////////////////////////////////////////////////////////////////////////////////////////
- (void)requestFailed:(ASIHTTPRequest *)request
{
    NSError *error = [request error];
}

#pragma mark -
#pragma mark ANIProgressDelegate

// Called when the request receives some data - bytes is the length of that data
- (void)request:(ASIHTTPRequest *)request didReceiveBytes:(long long)bytes
{
    NSLog(@"didReceiveBytes:%d", bytes);
}

#pragma mark -
#pragma mark NSURLConnectionDelegate


///////////////////////////////////////////////////////////////////////////////////////////////////
- (void)connection:(NSURLConnection*)connection 
                    didReceiveResponse:(NSHTTPURLResponse*)response {
    NSLog(@"%@-- didReceiveResponse", _urlPath);
    
    _response = [response retain];
     
    [_responseData setLength:0];
}


///////////////////////////////////////////////////////////////////////////////////////////////////
- (void)connection:(NSURLConnection*)connection didReceiveData:(NSData*)data {
    //NSLog(@"%@-- didReceiveData", _url);
    [_responseData appendData:data];
}


///////////////////////////////////////////////////////////////////////////////////////////////////
- (NSCachedURLResponse *)connection: (NSURLConnection *)connection
                  willCacheResponse: (NSCachedURLResponse *)cachedResponse {
    NSLog(@"%@-- willCacheResponse", _urlPath);
    return nil;
}


///////////////////////////////////////////////////////////////////////////////////////////////////
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
    NSLog(@"%@-- %d connectionDidFinishLoading", _urlPath, _response.statusCode);
    // We need to accept valid HTTP status codes, not only 200.
    if (_response.statusCode >= 200 && _response.statusCode < 300) {
        self.image = [UIImage imageWithData:_responseData];
        [self setNeedsLayout];
    } else if (_response.statusCode == 304) {

    } else {
    }
}


///////////////////////////////////////////////////////////////////////////////////////////////////
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
    NSLog(@"%@-- didFailWithError", _urlPath);
}


@end
